package com.geostar.constructionland.analyse.controller;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.geostar.constructionland.analyse.entity.model.AnalyseModel;
import com.geostar.constructionland.analyse.entity.resulthandler.HandlerResult;
import com.geostar.constructionland.analyse.service.AnalyseService;
import com.geostar.constructionland.analyse.service.HttpAPIService;
import com.geostar.constructionland.analyse.service.automatic.AutomaticService;
import com.geostar.constructionland.analyse.service.automatic.util.FileUtil;
import com.geostar.constructionland.analyse.service.automatic.util.Md5Util;
import com.geostar.constructionland.analyse.service.geohandler.CoordinateService;
import com.geostar.constructionland.analyse.valid.GeoAnalyseVaild;
import com.geostar.constructionland.analyse.validtor.ValidAnalyseModelRule;
import com.geostar.constructionland.common.entity.response.ResponseCode;
import com.geostar.constructionland.common.entity.response.ServerResponse;
import com.geostar.constructionland.common.util.CpdetectorEncoding;
import io.swagger.annotations.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.InetAddress;
import java.net.URLEncoder;
import java.nio.charset.Charset;
import java.util.*;

/**
 * @author yelll
 * @since 2020-5-26 9:43
 **/
@Slf4j
@Api(value = "建设用地分析模块")
@Validated
@RestController
public class AnalyseController {
    @Autowired
    AnalyseService analyseService;
    @Autowired
    AutomaticService automaticService;

    @Autowired
    CoordinateService coordinateService;
    @ApiModelProperty(value = "批量导入坐标文件")
    @PostMapping(value = "/importCoordinates")
    @ResponseBody
    public ServerResponse importCoordinates(@RequestParam(value="files")List<MultipartFile> list,
                                            @RequestParam("ywid") String ywid, @RequestParam("yhid") String yhid,
                                            @RequestParam("newId") String newId, @RequestParam("zblx") String zblx)
            throws Exception{
        return coordinateService.coordinateFileImport(list,ywid,yhid,newId, zblx);
    }

    @ApiModelProperty(value = "从服务器批量导入坐标文件")
    @PostMapping(value = "/importCoordinatesFromServer")
    @ResponseBody
    public ServerResponse importCoordinatesFromServer(@RequestParam(value = "fileIdNameList") List<String> fileIdNameList,
                                                      @RequestParam("ywid") String ywid, @RequestParam("yhid") String yhid,
                                                      @RequestParam("newId") String newId, @RequestParam("zblx") String zblx)
            throws Exception {
        return coordinateService.importCoordinatesFromServer(fileIdNameList, ywid, yhid, newId, zblx);
    }

    @ApiOperation(value = "文件上传分析")
    @PostMapping(value = "/uploadAnalyse")
    @ResponseBody
    public ServerResponse uploadAnalyse(@RequestParam("file") MultipartFile file,
                                        @RequestParam("userId") String userId){
        ServerResponse serverResponse = ServerResponse.createByErrorMessage("上传文件失败");
        if (file.isEmpty()) {
            return ServerResponse.createByErrorMessage("上传失败，文件为空！");
        }
        String fileName = file.getOriginalFilename();
        try {
            CpdetectorEncoding cpdetectorEncoding = new CpdetectorEncoding();
            /**获取文件编码*/
            Charset charsetName = cpdetectorEncoding.getFastEncoding(file.getBytes());
            if(charsetName.name().equals("x-EUC-TW")){
                charsetName = Charset.forName("GBK");
            }
            String content = new String(file.getBytes(),charsetName);
            log.info("fileName:{},fileContent:{}",fileName,content);
            serverResponse = automaticService.automatic(content,fileName,Md5Util.getFileMD5(file),userId);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return serverResponse;
    }

    @ApiOperation(value = "批量文件上传分析")
    @PostMapping(value = "/batchUploadAnalyse")
    @ResponseBody
    public ServerResponse batchUploadAnalyse(@RequestParam("file") MultipartFile[] files){
        for (int i = 0; i < files.length; i++) {
            MultipartFile file = files[i];
            String fileName = file.getOriginalFilename();
            try {
                String content = new String(file.getBytes());
                log.info("文件内容:{}",content);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return null;
    }

    @ApiOperation(value = "分析接口")
    @PostMapping(value = "/analyse")
    @ResponseBody
    public HandlerResult analyse(@RequestBody @ValidAnalyseModelRule AnalyseModel analyseModel) throws Exception {
        log.info("服务器地址是：{} ,analyseModel是: {}", InetAddress.getLocalHost().getHostAddress(),analyseModel.toString());
        HandlerResult handlerResult;
        try {
            handlerResult = analyseService.analyse(analyseModel);
            handlerResult.setMessage(analyseModel.getFxlx());
        }catch (Exception e){
            handlerResult = HandlerResult.createByErrorMessage(e.getMessage());
        }
        return handlerResult;
    }

    @ApiModelProperty(value = "GEOJSON分析接口")
    @PostMapping(value = "/analyse/geojson")
    public HandlerResult analysByGeoJson(@RequestBody @Validated(GeoAnalyseVaild.class) AnalyseModel analyseModel) throws Exception{
        log.info("服务器地址是：{} ,analyseModel是: {}", InetAddress.getLocalHost().getHostAddress(),analyseModel.toString());
        /**设置ID**/
        HandlerResult handlerResult = analyseService.analyseJson(analyseModel);
        handlerResult.setMessage(analyseModel.getAlyId());
        return handlerResult;
    }

    @ApiModelProperty(value = "供给矿产系统分析服务")
    @PostMapping(value = "/analyse/mineAnalyse")
    public String mineAnalyse(@RequestBody @Validated(GeoAnalyseVaild.class) AnalyseModel analyseModel) throws Exception{
        HandlerResult handlerResult = analyseService.analyseJson(analyseModel);
        return handlerResult.getData().toString();
    }


    @Autowired
    ObjectMapper objectMapper;

    @ApiOperation(value = "批量导出结果")
    @GetMapping(value = "/batchExport")
    public void batchExport(@RequestParam("ywids") String ywids, HttpServletResponse response) throws Exception{
        String zipPath = automaticService.batchExport(ywids);
        File zipFile = new File(zipPath);
        if (zipFile.exists()) {
            // 配置文件下载
            response.setHeader("content-type", "application/octet-stream");
            response.setContentType("application/octet-stream");
            // 下载文件能正常显示中文
            response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(zipFile.getName(), "UTF-8"));
            // 实现文件下载
            byte[] buffer = new byte[1024];
            FileInputStream fis = null;
            BufferedInputStream bis = null;
            try {
                fis = new FileInputStream(zipFile);
                bis = new BufferedInputStream(fis);
                OutputStream os = response.getOutputStream();
                int i = bis.read(buffer);
                while (i != -1) {
                    os.write(buffer, 0, i);
                    i = bis.read(buffer);
                }
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                if (bis != null) {
                    try {
                        bis.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                if (fis != null) {
                    try {
                        fis.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }


    @Autowired
    HttpAPIService httpAPIService;
    @ApiOperation(value = "批量分析")
    @PostMapping(value = "/batchAnalyse")
    @ResponseBody
    public ServerResponse batchAnalyse(@RequestParam("ywid") String ywid,@RequestParam("qsnd") String qsnd,@RequestParam("gdnd") String gdnd,@RequestParam("dlnd") String dlnd) throws Exception{

        return analyseService.batchAnalyse(ywid,qsnd,gdnd,dlnd);
    }

    @ApiOperation(value = "基础班坐标批量转换政务版坐标")
    @PostMapping(value = "/batchTransCoord")
    @ResponseBody
    public void batchTransCoord(@RequestParam("file") MultipartFile[] files,HttpServletResponse response) throws Exception {
        ServerResponse serverResponse = automaticService.batchTransCoord(files);

        if(serverResponse.getStatus() == ResponseCode.SUCCESS.getCode()) {
            String zipPath = (String) serverResponse.getData();
            File zipFile = new File(zipPath);
            if (zipFile.exists()) {
                // 配置文件下载
                response.setHeader("content-type", "application/octet-stream");
                response.setContentType("application/octet-stream");
                // 下载文件能正常显示中文
                response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(zipFile.getName(), "UTF-8"));
                // 实现文件下载
                byte[] buffer = new byte[1024];
                FileInputStream fis = null;
                BufferedInputStream bis = null;
                OutputStream os = null;
                try {
                    fis = new FileInputStream(zipFile);
                    bis = new BufferedInputStream(fis);
                    os = response.getOutputStream();
                    int i = bis.read(buffer);
                    while (i != -1) {
                        os.write(buffer, 0, i);
                        i = bis.read(buffer);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    try {
                        if (os != null) {
                            os.close();
                        }
                        if (bis != null) {
                            bis.close();
                        }
                        if (fis != null) {
                            fis.close();
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    // 删除压缩包
                    FileUtil.delFile(zipPath);
                }
            }
        }
    }
}
